package com.efun.framework.validate;

import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorChain;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <pre>
 *     @Bean
 * </pre>
 * Created by kinven on 17-8-21.
 */
public class ValidatorManager implements InitializingBean,ApplicationContextAware,BeanNameAware {

    private static final Log LOG = LogFactory.getLog(ValidatorManager.class);

    ApplicationContext applicationContext;
    String beanName;
    String defaultClassNames;
    private static final Map<String,Validator> validatorMap = new LinkedHashMap<String,Validator>();
    private static final ValidatorChain validatorChain = new ValidatorChain();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public void setDefaultValidator(String className){
        this.defaultClassNames = className;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String,Validator> all = applicationContext.getBeansOfType(Validator.class);
        for(Validator v : all.values()){
            register(v);
        }
        Assert.notNull(defaultClassNames,"default validator properties is null");

        List<Validator> defaultValidators = new LinkedList<Validator>();
        for(String name : StringUtils.tokenizeToStringArray(defaultClassNames,",")){
            if (validatorMap.containsKey(name)) {
                defaultValidators.add(validatorMap.get(name));
            }
        }
        validatorChain.setValidators(defaultValidators);

    }

    public void register(Validator validator) {
        validatorMap.put(validator.getClass().getSimpleName(),validator);
    }

    public Validator getValidator(Class<?> clazz){
        if(validatorMap.containsKey(clazz.getSimpleName())){
            return validatorMap.get(clazz.getSimpleName());
        }
        LOG.info("can not found the class" + clazz.getName());
        return null ;
    }

    public Validator getValidator(String className){
        if(validatorMap.containsKey(className)){
            return validatorMap.get(className);
        }
        LOG.info("can not found the class" + className);
        return null ;
    }

    public ValidatorChain getDefaultValidator(){
        return this.validatorChain;
    }

}
